<template>
  <div>
    <el-cascader
      v-model="value"
      :options="areaOptions"
      :props="cascaderProps"
      :placeholder="setting.writerPlaceholder || '请选择地区'"
      clearable
      :show-all-levels="true"
      :disabled="props.disabled"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import areaData from '@/assets/area-code.json'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  setting: {
    type: Object,
    default: () => {}
  },
  formRules: {
    type: Object,
    default: () => {}
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue', 'update:formRules'])

const value = computed({
  get: () => props.modelValue.split('-'),
  set: (val) => {
    if (JSON.stringify(val) === JSON.stringify(value.value)) {
      return
    }
    emits('update:modelValue', val.join('-'))
  }
})

const formRules = computed({
  get: () => props.formRules,
  set: (val) => {
    emits('update:formRules', val)
  }
})

// 地区数据
const areaOptions = ref(areaData)

// 级联选择器配置
const cascaderProps = computed(() => ({
  value: 'name',
  label: 'name',
  children: 'children',
  checkStrictly: false,
  expandTrigger: 'hover',
  multiple: false,
  level: props.setting.district
}))

// 生成校验规则
const generateRules = () => {
  const rules = []
  
  if (props.setting.require) {
    rules.push({ 
      required: true, 
      message: '此题为必填题', 
      trigger: 'change' 
    })
  }

  formRules.value[props.setting.formItemId] = rules
}

onMounted(() => {
  generateRules()
})
</script>

<style lang='scss' scoped>
:deep(.el-cascader) {
  width: 100%;
}
</style>